package lichunUtil;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;

public final class SimpleReader implements Iterable<String> {

	private ReadlineIterator ri;

	public SimpleReader(String filepath, String charsetname) {
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(filepath), charsetname));
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(0);
		}
		this.ri = new ReadlineIterator(br);
	}
	
	public SimpleReader(String filepath) {
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(filepath));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.exit(0);
		}
		this.ri = new ReadlineIterator(br);
	}

	public SimpleReader(BufferedReader br) {
		this.ri = new ReadlineIterator(br);
	}
	
	@Override
	public Iterator<String> iterator() {
		return ri;
	}

	static public void selftest() {
		SimpleReader sr = new SimpleReader("d:/testfile.txt");
		System.out.println("---start---");
		for (String in : sr)
			System.out.println(in);

	}

	static private class ReadlineIterator implements Iterator<String> {

		private String buffer;
		private BufferedReader br;

		public ReadlineIterator(BufferedReader br) {
			this.br = br;
		}

		@Override
		public boolean hasNext() {
			try {
				buffer = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
				System.exit(0);
			}
			if (buffer == null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return false;
			} else
				return true;

		}

		@Override
		public String next() {
			return buffer;
		}

		@Override
		public void remove() {
			// does not make sense
			System.err.println("unexpected call: ReadlineIterator---remove()");
			System.exit(0);
		}
	}
}
